package com.bookstore.servlet.admin;

import com.google.gson.Gson;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.UUID;
@MultipartConfig(location = "F:\\train\\demo\\javaweb2112\\bookstore\\web\\uploadImg", fileSizeThreshold = 1024 * 1024, maxFileSize = 1024 * 1024 * 5, maxRequestSize = 1024 * 1024 * 5 * 5)
@WebServlet("/admin/uploadImgs.do")
public class UploadServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf-8");
        PrintWriter writer = resp.getWriter();
        try {
            Part part = req.getPart("productImg");
            String submittedFileName = part.getSubmittedFileName();
            String type = submittedFileName.substring(submittedFileName.lastIndexOf("."));
            String filename = UUID.randomUUID().toString() + type;
            String path = "F:\\train\\demo\\javaweb2112\\bookstore\\web\\uploadImg\\" + filename;
            part.write(path);
            writer.write(new Gson().toJson(filename));
        } catch (Exception e) {
            writer.write(new Gson().toJson(0));
        }
    }
}
